package com.xxjqr.rbac.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class PageUtil<T> {

    private final HttpServletRequest request;

    {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        request = servletRequestAttributes.getRequest();
    }

    public IPage<T> getPage() {
        Page<T> objectPage = new Page<>();
        String size = request.getParameter("size");
        String current = request.getParameter("current");
        try {
            if (!StringUtils.hasLength(size)) {
                objectPage.setSize(10);
            } else {
                objectPage.setSize(Long.parseLong(size));
            }
            if (!StringUtils.hasLength(current)) {
                objectPage.setCurrent(1);
            } else {
                objectPage.setCurrent(Long.parseLong(current));
            }
        } catch (Exception e) {
            log.error("分页参数解析错误 {}", e.getMessage());
            e.printStackTrace();
        }
        return objectPage;
    }
}
